let udp = null;
// pages/main/main.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showAddMenu: false, // 控制添加菜单弹窗显示
    showEditDialog: false, // 控制编辑设备名称弹窗显示
    tempDeviceName: '', // 临时输入的设备名称

    deviceList: [{
      deviceId: 'device001',
      deviceName: '吧唧之王',
      macAddress: 'A4:CF:12:3B:9F:88',
      firmwareVersion: 'v1.0.0',
      hardwareVersion: 'C3-Display-RevA',
      productSeries: 'ChiYu Baji -360',
      bindingStatus: '已绑定',
      boundUser: 'abcd1234',
      touchAuth: '已授权',
      authExpireTime: '2025-11-30 12:00:00',
      networkType: 'Wi-Fi',
      wifiSignalStrength: '-58 dBm',
      deviceIp: '192.168.1.102',
      totalStorage: '2048 KB',
      usedStorage: '512 KB',
      storageUsage: '25%',
      storedImages: '10 张',
      maxStorage: '60 张',
      batteryVoltage: '3.92 V',
      batteryLevel: '86%',
      uptime: '1,023,456 ms',
      securityCode: '684321',
      checksum: 'e8f7ab29d4...',
      systemTimestamp: '1,023,456',
      connected: true,
      imageList: [{
        path: '/statics/images/CHYRAE_icon.png',
        name: 'image_1',
        size: 100,
        type: 'image/jpeg',
        uploadTime: new Date().toISOString()
      }, {
        path: '/statics/images/CHYRAE_icon.png',
        name: 'image_2',
        size: 100,
        type: 'image/jpeg',
        uploadTime: new Date().toISOString()
      }]
    },
    {
      deviceId: 'device002',
      deviceName: '大吧唧',
      macAddress: 'B5:DG:23:4C:0A:99',
      firmwareVersion: 'v1.1.0',
      hardwareVersion: 'C3-Display-RevA',
      productSeries: 'ChiYu Baji -360',
      bindingStatus: '已绑定',
      boundUser: 'efgh5678',
      touchAuth: '已授权',
      authExpireTime: '2025-12-31 12:00:00',
      networkType: 'Wi-Fi',
      wifiSignalStrength: '-62 dBm',
      deviceIp: '192.168.1.103',
      totalStorage: '2048 KB',
      usedStorage: '1024 KB',
      storageUsage: '50%',
      storedImages: '25 张',
      maxStorage: '60 张',
      batteryVoltage: '3.85 V',
      batteryLevel: '75%',
      uptime: '2,045,678 ms',
      securityCode: '785432',
      checksum: 'f9g8bc39e5...',
      systemTimestamp: '2,045,678',
      connected: false,
      imageList: [{
        path: '/statics/images/CHYRAE_icon.png',
        name: 'image_1',
        size: 100,
        type: 'image/jpeg',
        uploadTime: new Date().toISOString()
      }]
    }], // 设备列表
    currentDeviceIndex: 0, // 当前选中的设备索引
    isSwitching: false, // 是否正在切换设备（用于动画控制）
    cardAnimation: {}, // 卡片动画对象
    currentDevice: null, // 当前选中的设备

    connected: false, // 是否连接
    searching: true, // 是否正在搜索
    isPairing: false, // 是否正在配网
    logList: [], // 日志列表
    phoneIP: "", // 手机 IP
    deviceInfo: null, // 设备信息
    deviceTable: [], // 设备表格
    uploadImagePath: "", // 上传图片路径
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.addLog("小程序启动，自动搜索小车中...");
    this.listenUDP();
    // 初始化设备显示（如果有已保存的设备列表）
    this.updateCurrentDevice();
    // 从本地存储恢复设备列表
    const deviceList = wx.getStorageSync('deviceList');
    if (deviceList && deviceList.length > 0) {
      this.setData({ deviceList: deviceList });
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    // 初始化卡片动画，确保卡片初始可见且在中心位置
    const animation = wx.createAnimation({
      duration: 0
    });
    animation.translateX(0).opacity(1).step();
    this.setData({
      cardAnimation: animation.export()
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 页面显示时，如果有设备列表，默认显示第一个设备
    this.updateCurrentDevice();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  // ------------------------- ✅ 日志记录 -------------------------
  addLog(msg) {
    console.log(`[${new Date().toLocaleTimeString()}] ${msg}`);
    const list = this.data.logList;
    list.push(`[${new Date().toLocaleTimeString()}] ${msg}`);
    this.setData({ logList: list });
  },

  // ------------------------- ✅ UDP 广播监听 -------------------------
  async listenUDP() {
    this.addLog("监听UDP端口 4210 中...");
    udp = wx.createUDPSocket();
    udp.bind(4210);
    udp.onMessage((res) => {
      const msg = String.fromCharCode.apply(null, new Uint8Array(res.message));
      if (msg.startsWith("connected@")) {
        const ip = msg.split("@")[1];
        // 检查设备是否已存在（避免重复添加）
        const existingDevice = this.data.deviceList.find(device => device.ip === ip);
        if (!existingDevice) {
          const currentList = this.data.deviceList;
          this.assemblyDeviceInfo(ip).then(res => {
            const newDevice = res
            const updatedList = [...currentList, newDevice];
            this.setData({
              deviceList: updatedList
            });
            // 将deviceList放入本地存储，用于下次打开小程序时恢复
            wx.setStorageSync('deviceList', updatedList);
            // 如果是第一个设备，自动设置为当前设备
            if (currentList.length === 0) {
              this.setData({
                currentDeviceIndex: 0,
                currentDevice: newDevice,
                deviceName: newDevice.name
              });
            }
            this.addLog(`设备上线，IP=${ip}`);
            wx.showToast({ title: "已发现设备", icon: "success" });
          });
        } else {
          // 设备已存在，更新设备状态
          existingDevice.connected = true;
          // 将existingDevice重新放入this.data.deviceList中
          const currentList = this.data.deviceList;
          const index = currentList.findIndex(device => device.ip === ip);
          if (index !== -1) {
            currentList[index] = existingDevice;
            this.setData({ deviceList: currentList });
          }
        }
        udp.send({ address: ip, port: 4210, message: "9" });
      }
    });
  },

  assemblyDeviceInfo(ip) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: `http://${ip}/device/info`,
        method: "GET",
        success: (res) => {
          const info = typeof res.data === "string" ? JSON.parse(res.data) : res.data;
          resolve({
            deviceIp: info.device_ip,
            deviceName: info.device_name,
            deviceId: info.device_id,
            firmwareVersion: info.firmware_ver,
            hardwareVersion: info.hardware_rev,
            activationUID: info.activation_uid,
            touchAuthorized: info.touch_authorized,
            touchExpireAt: info.touch_expire_at,
            secureNonce: info.secure_nonce,
            timestamp: info.timestamp,
            checkSum: info.check_sum,
            uptimeMs: info.uptime_ms,
            connectType: info.connect_type,
            signalStrength: info.signal_strength,
            connected: true,
            imageList: []
          });
        },
        fail: (err) => {
          console.log("获取设备信息失败", err);
          reject(err);
        }
      });
    });
  },

  /**
   * 更新当前显示的设备
   */
  updateCurrentDevice() {
    const { deviceList, currentDeviceIndex } = this.data;
    if (deviceList.length > 0) {
      const index = Math.min(currentDeviceIndex, deviceList.length - 1);
      const device = deviceList[index];
      this.setData({
        currentDeviceIndex: index,
        currentDevice: device,
        deviceName: device.deviceName || `设备_${index + 1}`
      });
    } else {
      this.setData({
        currentDeviceIndex: 0,
        currentDevice: null,
        deviceName: '吧唧之王'
      });
    }
  },

  // ------------------------- ✅ 控制指令 -------------------------
  sendCommandStart(e) {
    const cmd = e.currentTarget.dataset.cmd;
    if (!this.data.currentDevice.ip) return;
    udp.send({ address: this.data.carIP, port: 4210, message: cmd });
    this.addLog(`发送控制指令：${cmd}`);
  },

  sendCommandEnd() {
    if (!this.data.currentDevice.ip) return;
    udp.send({ address: this.data.carIP, port: 4210, message: "0" });
    this.addLog("松开按钮，发送停止指令");
  },

  sendStop() {
    if (!this.data.currentDevice.ip) return;
    udp.send({ address: this.data.carIP, port: 4210, message: "0" });
    this.addLog("发送停止指令");
  },

  clearWiFi() {
    if (!this.data.currentDevice.ip) return;
    wx.showModal({
      title: "确认操作",
      content: "确定要清除小车已保存的WiFi吗？小车将恢复为热点模式",
      success: (res) => {
        if (res.confirm) {
          udp.send({ address: this.data.carIP, port: 4210, message: "8" });
          this.addLog("已发送清除WiFi指令");
          wx.showToast({ title: "已发送清除指令", icon: "none" });
        }
      },
    });
  },

  sendSingleCommand(e) {
    const cmd = e.currentTarget.dataset.cmd;
    if (!this.data.currentDevice.ip) return;
    if (!this.data.currentDevice.ip) return;
    udp.send({ address: this.data.currentDevice.ip, port: 4210, message: cmd });
    this.addLog(`发送瞬时指令：${cmd}`);
  },

  // ------------------------- ✅ 设备信息处理 -------------------------
  buildDeviceTable(info) {
    return [
      { label: "设备名称", value: info.device_name || "-" },
      { label: "设备ID", value: info.device_id || "-" },
      { label: "固件版本", value: info.firmware_ver || "-" },
      { label: "硬件版本", value: info.hardware_rev || "-" },
      { label: "触摸授权", value: info.touch_authorized ? "已授权" : "未授权" },
      { label: "授权到期", value: info.touch_expire_at || "无" },
      {
        label: "WiFi信号强度",
        value: (info.signal_strength ?? "N/A") + " dBm",
      },
      { label: "当前连接", value: info.connect_type || "-" },
      { label: "设备IP", value: info.device_ip || "-" },
      { label: "运行时长", value: (info.uptime_ms || 0) + " ms" },
    ];
  },

  logDeviceInfo(info) {
    const lines = [
      `设备名称: ${info.device_name || "-"}`,
      `设备ID: ${info.device_id || "-"}`,
      `固件版本: ${info.firmware_ver || "-"}`,
      `硬件版本: ${info.hardware_rev || "-"}`,
      `触摸授权: ${info.touch_authorized ? "已授权" : "未授权"}`,
      `授权到期: ${info.touch_expire_at || "无"}`,
      `连接方式: ${info.connect_type || "-"}`,
      `设备IP: ${info.device_ip || "-"}`,
      `信号强度: ${info.signal_strength ?? "N/A"} dBm`,
      `运行时长: ${info.uptime_ms || 0} ms`,
    ];
    lines.forEach((l) => this.addLog(l));
  },

  onPhoneIPInput(e) {
    this.setData({ phoneIP: e.detail.value });
  },

  sendPhoneIP() {
    const { phoneIP, carIP } = this.data;
    if (!phoneIP) {
      wx.showToast({ title: "请输入手机IP", icon: "none" });
      return;
    }
    this.addLog(`下发手机IP至设备：${phoneIP}`);
    const ip = carIP || "192.168.1.100";
    wx.request({
      url: `http://${ip}/device/info`,
      method: "GET",
      success: (res) => {
        const info =
          typeof res.data === "string" ? JSON.parse(res.data) : res.data;
        this.addLog("收到设备信息，开始解析...");
        this.logDeviceInfo(info);
        const deviceTable = this.buildDeviceTable(info);
        this.setData({ deviceInfo: info, deviceTable });
        this.fakeServerRegister(info);
      },
      fail: () => {
        this.addLog("访问设备失败，请检查IP或连接状态");
      },
    });
  },

  fakeServerRegister(deviceInfo) {
    this.addLog("模拟服务器注册中...");
    setTimeout(() => {
      const token =
        "FAKE-" + Math.random().toString(36).substring(2, 8).toUpperCase();
      this.addLog("服务器注册成功，Token=" + token);
      this.setData({ fakeToken: token });
    }, 800);
  },

  // ------------------------- ✅ 图片选择与裁剪 -------------------------
  chooseImage() {
    wx.chooseImage({
      count: 1,
      sizeType: ["compressed"],
      success: (res) => {
        const path = res.tempFilePaths[0];
        console.log("[Index] 选择的图片路径:", path);
        this.setData({ uploadImagePath: path });
        wx.setStorageSync("tempCropPath", path);
        wx.navigateTo({
          url: "/pages/index/crop/crop",
          success: (res) => {
            res.eventChannel.on("cropDone", (data) => {
              console.log("[Index] 裁剪完成，接收到路径:", data.path);
              this.setData({ uploadImagePath: data.path });
              this.compressAndUpload()
            });
          },
        });
      },
      fail: () => wx.showToast({ title: "未选择图片", icon: "none" }),
    });
  },

  editImage() {
    const path = this.data.uploadImagePath || wx.getStorageSync("tempCropPath");
    if (!path) {
      wx.showToast({ title: "请先选择图片", icon: "none" });
      return;
    }
    wx.setStorageSync("tempCropPath", path);
    wx.navigateTo({
      url: "/pages/index/crop/crop",
      success: (res) => {
        res.eventChannel.on("cropDone", (data) => {
          console.log("[Index] 裁剪完成，接收到路径:", data.path);
          this.setData({ uploadImagePath: data.path });
          wx.setStorageSync("tempCropPath", data.path);
        });
      },
    });
  },

  // ------------------------- ✅ 图片压缩与上传 -------------------------
  // ------------------------- ✅ 压缩并上传图片（带详细日志） -------------------------
  compressAndUpload() {
    const _this = this;
    const path = this.data.uploadImagePath;

    if (!path) {
      wx.showToast({ title: "请先选择并裁剪图片", icon: "none" });
      _this.addLog("⚠️ 未选择图片，压缩终止");
      return;
    }

    _this.addLog("🌀 [压缩流程] 开始获取图片信息...");
    wx.getImageInfo({
      src: path,
      success(info) {
        const { width, height } = info;
        const size = 240;
        const scale = Math.min(width, height) / size;
        const sx = (width - size * scale) / 2;
        const sy = (height - size * scale) / 2;

        _this.addLog(`📐 图片原始尺寸：${width}x${height}，裁剪中心区域`);
        _this.addLog("🖼️ 绘制到隐藏 canvas 中...");
        const ctx = wx.createCanvasContext("cropCanvas", _this);
        ctx.drawImage(
          path,
          sx,
          sy,
          size * scale,
          size * scale,
          0,
          0,
          size,
          size
        );

        ctx.draw(false, () => {
          _this.addLog("🔄 Canvas绘制完成，开始导出 JPG...");

          wx.canvasToTempFilePath({
            canvasId: "cropCanvas",
            destWidth: size,
            destHeight: size,
            fileType: "jpg",
            quality: 0.35,
            success: (res) => {
              const finalPath = res.tempFilePath;

              const fs = wx.getFileSystemManager();
              fs.stat({
                path: finalPath,
                success(statRes) {
                  const kb = (statRes.size / 1024).toFixed(1);
                  _this.addLog(`✅ 压缩成功，输出尺寸 240x240，大小约 ${kb}KB`);
                },
                fail() {
                  _this.addLog("⚠️ 无法读取压缩后文件大小");
                },
              });

              _this.setData({ uploadImagePath: finalPath });
              _this.addLog("📤 准备上传...");
              _this._uploadWithProgress(finalPath);
            },
            fail: (err) => {
              wx.showToast({ title: "压缩失败", icon: "none" });
              _this.addLog("❌ 压缩失败：" + err.errMsg);
            },
          });
        });
      },
      fail: () => {
        wx.showToast({ title: "图片信息获取失败", icon: "none" });
        _this.addLog("❌ 获取图片信息失败");
      },
    });
  },
  _uploadWithProgress(filePath) {
    const currentDevice = this.data.currentDevice;
    const carIP = currentDevice?.deviceIp || currentDevice?.ip;
    if (!carIP || !currentDevice?.connected) {
      wx.showToast({ title: "未连接设备", icon: "none" });
      this.addLog("❌ 上传失败：未获取到设备 IP");
      return;
    }

    this.addLog("🚀 正在上传至设备...");
    wx.showLoading({ title: "上传中 0%", mask: true });

    const uploadTask = wx.uploadFile({
      url: `http://${carIP}/upload`,
      filePath: filePath,
      name: "file",
      success: (res) => {
        wx.hideLoading();
        if (res.statusCode === 200) {
          wx.showToast({ title: "上传成功", icon: "success" });
          this.addLog(`✅ 上传成功，设备返回：${res.data}`);
          // 更新deviceList中的设备图片
          const currentList = this.data.deviceList;
          const index = currentList.findIndex(device => 
            (device.deviceIp || device.ip) === carIP
          );
          if (index !== -1) {
            // 获取文件大小
            const fs = wx.getFileSystemManager();
            fs.stat({
              path: filePath,
              success: (statRes) => {
                const imageList = currentList[index].imageList || [];
                imageList.push({
                  path: filePath,
                  name: `image_${imageList.length + 1}`,
                  size: statRes.size,
                  type: 'image/jpeg',
                  uploadTime: new Date().toISOString()
                });
                currentList[index].imageList = imageList;
                this.setData({ deviceList: currentList });
                wx.setStorageSync('deviceList', currentList);
                this.updateCurrentDevice();
              },
              fail: () => {
                // 如果获取文件大小失败，仍然添加图片信息
                const imageList = currentList[index].imageList || [];
                imageList.push({
                  path: filePath,
                  name: `image_${imageList.length + 1}`,
                  size: 0,
                  type: 'image/jpeg',
                  uploadTime: new Date().toISOString()
                });
                currentList[index].imageList = imageList;
                this.setData({ deviceList: currentList });
                wx.setStorageSync('deviceList', currentList);
                this.updateCurrentDevice();
              }
            });
          }
        } else {
          wx.showToast({ title: "上传失败", icon: "none" });
          this.addLog(`❌ 上传失败，状态码：${res.statusCode}`);
        }
      },
      fail: (err) => {
        wx.hideLoading();
        wx.showToast({ title: "上传异常", icon: "none" });
        this.addLog(`❌ 上传异常：${err.errMsg}`);
      },
    });

    uploadTask.onProgressUpdate((res) => {
      wx.showLoading({ title: `上传中 ${res.progress}%`, mask: true });
      if (res.progress % 10 === 0) {
        this.addLog(`📶 上传进度：${res.progress}%`);
      }
    });
  },

  /**
   * 返回按钮点击事件
   */
  onBackTap() {
    wx.navigateTo({
      url: '/pages/device/device'
    });
  },

  /**
   * 消息按钮点击事件
   */
  onMessageTap() {
    // TODO: 跳转到消息页面
    console.log('点击消息');
  },

  /**
   * 左箭头点击事件 - 切换到上一个设备
   */
  onPrevTap() {
    const { deviceList, currentDeviceIndex, isSwitching } = this.data;
    if (deviceList.length === 0 || isSwitching) {
      return;
    }
    const newIndex = currentDeviceIndex > 0 
      ? currentDeviceIndex - 1 
      : deviceList.length - 1; // 循环到最后一个
    
    // 开始切换动画（向左滑动：当前卡片向右滑出，新卡片从左侧滑入）
    this.startSwitchAnimation('left', () => {
      this.setData({
        currentDeviceIndex: newIndex
      });
      this.updateCurrentDevice();
    });
  },

  /**
   * 右箭头点击事件 - 切换到下一个设备
   */
  onNextTap() {
    const { deviceList, currentDeviceIndex, isSwitching } = this.data;
    if (deviceList.length === 0 || isSwitching) {
      return;
    }
    const newIndex = currentDeviceIndex < deviceList.length - 1 
      ? currentDeviceIndex + 1 
      : 0; // 循环到第一个
    
    // 开始切换动画（向右滑动：当前卡片向左滑出，新卡片从右侧滑入）
    this.startSwitchAnimation('right', () => {
      this.setData({
        currentDeviceIndex: newIndex
      });
      this.updateCurrentDevice();
    });
  },

  /**
   * 开始切换动画
   * @param {String} direction - 滑动方向：'left' 或 'right'
   * @param {Function} callback - 动画完成后的回调函数
   */
  startSwitchAnimation(direction, callback) {
    // 设置切换状态为true，防止重复点击
    this.setData({
      isSwitching: true
    });

    // 计算滑动距离（屏幕宽度，使用 rpx 单位，约 750rpx）
    const slideDistance = 750;
    const slideOutX = direction === 'left' ? slideDistance : -slideDistance;
    const slideInX = direction === 'left' ? -slideDistance : slideDistance;

    // 当前卡片滑出动画
    const animationOut = wx.createAnimation({
      duration: 300,
      timingFunction: 'ease-in-out'
    });

    animationOut.translateX(slideOutX).opacity(0).step();

    this.setData({
      cardAnimation: animationOut.export()
    });

    // 动画完成后更新设备并从另一侧滑入
    setTimeout(() => {
      if (callback) {
        callback();
      }

      // 新卡片从另一侧滑入动画
      const animationIn = wx.createAnimation({
        duration: 300,
        timingFunction: 'ease-in-out'
      });

      // 先设置到起始位置（屏幕外）
      animationIn.translateX(slideInX).opacity(0).step({
        duration: 0
      });

      // 然后滑入到中心位置
      animationIn.translateX(0).opacity(1).step({
        duration: 300,
        timingFunction: 'ease-in-out'
      });

      this.setData({
        cardAnimation: animationIn.export(),
        isSwitching: false
      });
    }, 300);
  },

  /**
   * 添加按钮点击事件
   */
  onAddTap() {
    console.log('添加图片');
    this.chooseImage();
  },

  /**
   * 图库标题右侧添加按钮点击事件
   */
  onGalleryAddTap() {
    this.setData({
      
      showAddMenu: true
    });
  },

  /**
   * 关闭添加菜单弹窗
   */
  closeAddMenu() {
    this.setData({
      showAddMenu: false
    });
  },

  /**
   * 新增吧唧按钮点击事件
   */
  onAddBadgeTap() {
    this.closeAddMenu();
    console.log('新增吧唧');
    wx.navigateTo({
      url: '/pages/device/add/add'
    });
  },

  /**
   * 新增图片按钮点击事件
   */
  onAddImageTap() {
    this.closeAddMenu();
    console.log('新增图片');
    this.chooseImage();
  },

  /**
   * 新增 GIF 按钮点击事件
   */
  onAddGifTap() {
    this.closeAddMenu();
    console.log('新增 GIF');
    // TODO: 实现新增 GIF 功能
  },

  /**
   * 新增视频按钮点击事件
   */
  onAddVideoTap() {
    this.closeAddMenu();
    console.log('新增视频');
    // TODO: 实现新增视频功能
  },

  /**
   * 标题区域点击事件 - 打开编辑弹窗
   */
  onTitleEditTap() {
    this.setData({
      showEditDialog: true,
      tempDeviceName: this.data.deviceName
    });
  },

  /**
   * 阻止事件冒泡
   */
  stopPropagation() {
    // 阻止事件冒泡，防止点击弹窗内部时关闭弹窗
  },

  /**
   * 关闭编辑设备名称弹窗
   */
  closeEditDialog() {
    this.setData({
      showEditDialog: false
    });
  },

  /**
   * 取消编辑
   */
  onCancelEdit() {
    this.closeEditDialog();
  },

  /**
   * 设备名称输入事件
   */
  onDeviceNameInput(e) {
    this.setData({
      tempDeviceName: e.detail.value
    });
  },

  /**
   * 保存设备名称
   */
  onSaveDeviceName() {
    const deviceName = this.data.tempDeviceName.trim();
    if (deviceName) {
      this.setData({
        showEditDialog: false
      });
      const currentDevice = this.data.currentDevice;
      currentDevice.name = deviceName;
      const currentList = this.data.deviceList;
      const index = currentList.findIndex(device => device.ip === currentDevice.ip);
      if (index !== -1) {
        currentList[index] = currentDevice;
        this.setData({ deviceList: currentList });
        wx.setStorageSync('deviceList', currentList);
      }
      wx.showToast({
        title: '保存成功',
        icon: 'success',
        duration: 1500
      });
    } else {
      wx.showToast({
        title: '设备名称不能为空',
        icon: 'none',
        duration: 1500
      });
    }
  }
})